<script setup lang="ts" name="AddTime">
import lodash from 'lodash'
import { createUUID } from '@/utils/ruoyi'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emits = defineEmits(['close', 'submit'])
/*========================================>( 模型属性 )<========================================*/
const show = ref<boolean>(false)
const labelOptions = ref<Array<any>>([])
const formData = ref<any>({
  label: undefined,
  timestamp: undefined,
  note: undefined,
  day: 0,
  hour: 0,
  min: 0,
  sec: 0,
})
const noteTags = ref<Array<string>>([])
/*========================================>( 作用域值 )<========================================*/
const _ipcs = {
  getData() {
    const { module, value } = window.ipcRenderer.sendSync('STORAGE-GET', { module: 'coc' })
    //如果所属本模块，更新模块设置数据
    if (module == 'coc') {
      labelOptions.value = value.labels
    }
  },
  add(task: any, label: string, labelName: string) {
    let tasks = undefined
    const { module, value } = window.ipcRenderer.sendSync('STORAGE-GET', { module: 'coc' })
    //如果所属本模块，更新模块设置数据
    if (module == 'coc') {
      tasks = value.tasks
    }
    //先寻找该组
    const group = tasks.find((e: any) => e.label === label)
    if (group) {
      group.list.push(task)
      tasks = [...tasks.filter((e: any) => e.label !== label), group]
    } else {
      tasks.push({
        label,
        labelName,
        list: [task]
      })
    }
    window.ipcRenderer.sendSync('STORAGE-SAVE', {
      module: 'coc',
      data: { tasks }
    })
  }
}
const _rules: any = {
  label: [
    { required: true, message: '请选择任务标签', trigger: ['blur', 'change'] },
  ],
  day: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!formData.value.day && !formData.value.hour && !formData.value.min && !formData.value.sec) {
          callback(new Error("请填写倒计时"))
        } else {
          callback()
        }
      }, trigger: ['blur', 'change']
    }
  ]
}
/*========================================>( 文档属性 )<========================================*/
const domForm = ref()
/*========================================>( 计算属性 )<========================================*/

/*========================================>( 普通方法 )<========================================*/
//关闭本modal
const close = () => {
  emits('close')
}
const addStorageTag = (note: string) => {
  if (noteTags.value.includes(note)) {
    return
  }
  noteTags.value.push(note)
  localStorage.setItem('coc-note-tags', JSON.stringify(noteTags.value))
}

const refreshStorageTag = () => {
  const store = localStorage.getItem('coc-note-tags')
  const storeTags = store ? JSON.parse(store) : []
  noteTags.value = storeTags
}

/*========================================>( 监听方法 )<========================================*/
//监听提交
const handleSubmit = () => {
  domForm.value.validate().then(() => {
    //格式化数据
    const entity = lodash.cloneDeep(formData.value)
    const exMils = Number(entity.day) * 86400000 + Number(entity.hour) * 3600000 + Number(entity.min) * 60000 + Number(entity.sec) * 1000
    const data = {
      id: createUUID(),
      waitMils: exMils,
      createdMils: new Date().getTime(),
      note: entity.note,
      status: 1
    }
    _ipcs.add(data, entity.label, labelOptions.value.find(e => e.id === entity.label).name)
    //把note加入缓存
    addStorageTag(entity.note)
    //添加完成，不关闭窗口，清空时间和备注
    formData.value.timestamp = undefined
    formData.value.note = undefined
    formData.value.day = 0
    formData.value.hour = 0
    formData.value.min = 0
    formData.value.sec = 0
    proxy?.$modal.msgSuccess('添加成功', 80)
  })

}

const handleClickTag = (item: string) => {
  formData.value.note = item
}

const handleTagRm = (item: string) => {
  noteTags.value = noteTags.value.filter(e => e != item)
  localStorage.setItem('coc-note-tags', JSON.stringify(noteTags.value))
}

/*========================================>( 钩子函数 )<========================================*/

/*========================================>( 默    认 )<========================================*/
onMounted(() => {
  _ipcs.getData()
  refreshStorageTag()
})

show.value = true

</script>
<template>
  <el-dialog class="add-time" v-model="show" width="90%" title="新增任务" @close="close" destroy-on-close>
    <el-form :model="formData" :rules="_rules" ref="domForm">
      <el-form-item label="标签" prop="label" required>
        <el-select v-model="formData.label" placeholder="请选择所属标签">
          <el-option v-for="item, index in labelOptions" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="计时" prop="day" required>
        <div class="time-box">
          <div class="pad">
            <el-input-number v-model="formData.day" :min="0" :max="20" />
            <div class="unit">天</div>
            <el-input-number v-model="formData.hour" :min="0" :max="23" />
            <div class="unit">时</div>
          </div>
          <div class="pad">
            <el-input-number v-model="formData.min" :min="0" :max="59" />
            <div class="unit">分</div>
            <el-input-number v-model="formData.sec" :min="0" :max="59" />
            <div class="unit">秒</div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="formData.note" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item>
        <span v-for="item in noteTags" :key="item" class="p-r-3-3 cursor-pointer">
          <el-tag type="info" closable @close="handleTagRm(item)" @click="handleClickTag(item)">{{ item }}</el-tag>
        </span>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.add-time {
  .time-box {
    height: 80px;

    .pad {
      padding: 5px 10px;
      display: flex;
      align-items: center;
      justify-content: center;

      .unit {
        padding: 0 20px 0 5px;
        font-weight: bold;
      }
    }
  }
}
</style>
